package com.sangeng.filter;

import com.alibaba.fastjson.JSON;
import com.sangeng.domain.ResponseResult;
import com.sangeng.domain.entity.LoginUser;
import com.sangeng.enums.AppHttpCodeEnum;
import com.sangeng.utils.JwtUtil;
import com.sangeng.utils.RedisCache;
import com.sangeng.utils.WebUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @auther qihs
 * @Date
 * 登录校验过滤器，需要添加到配置类中
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取请求头中的token     StringUtils.hasText(),如果为空，返回false，否则true
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            //说明该接口不需要登录，直接放行
            filterChain.doFilter(request, response);
            return;
        }
        //解析获取userId
        Claims claims = null;
        try {
            claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            /** 进入到catch的情况：1、token超时。2、token非法
             *     统一响应处理是针对controller层的，此处还没到，需要单独处理异常
             *     将异常响应信息封装为ResponseResult对象，然后转换为JSON 数据响应
             */
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtils.renderString(response, JSON.toJSONString(result));
            return;
        }
        // getSubject , 获取当前用户信息
        String userId = claims.getSubject();
        //从redis中获取用户信息。  注意与存入redis的key保持一致
        LoginUser loginUser = redisCache.getCacheObject("bloglogin:" + userId);
        //如果获取不到用户信息
        if (Objects.isNull(loginUser)){
            //说明登录信息过期 , 提示重新登陆
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtils.renderString(response, JSON.toJSONString(result));
            return;
        }

        //将用户信息封装为authentication对象，此处已认证，需要使用三参数，最后一个代表已认证状态
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, null ,null);

        //存入SecurityContextHolder,后面的过滤器从这里面取数据
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //返回，放行
        filterChain.doFilter(request, response);
    }
}
